/**
 * 
 */
package cn.gov.msa.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;

import cn.gov.msa.model.Menu;
import cn.gov.msa.model.MenuPermission;
import cn.gov.msa.model.Role;
import cn.gov.msa.model.UserDetail;
import cn.gov.msa.service.MenuPermissionService;
import cn.gov.msa.service.MenuService;
import cn.gov.msa.service.RoleService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@RestController
@RequestMapping(value = "/menu", produces = "text/plain;charset=UTF-8")
public class MenuController {

	ObjectMapper mapper = new ObjectMapper();
	@Autowired
	private MenuPermissionService menuPermissionService;
	@Autowired
	MenuService menuService;
	@Autowired
	RoleService roleService;

	@RequestMapping(value = "/findLeftMenu")
	public String findLeftMenu(HttpSession session, String menuCode) throws Exception {
		int result = 0;
		String info = "";
		JSONObject jsonResult = new JSONObject();

		try {
			String userID = session.getAttribute("userid").toString();
			UserDetail userDetail = (UserDetail)session.getAttribute("userDetail");
			List<Role> userRole = new ArrayList<>(); 
			for (Role role : userDetail.getRoles()) {
				if(role.getRolename().equals("业务受理") || role.getRolename().equals("制证") || role.getRolename().equals("发证")){
					userRole.add(role);
				}
				else if(role.getRolename().equals("业务初审") || role.getRolename().equals("业务复审") || role.getRolename().equals("业务审批")){
					Role r = new Role();
					r.setRolename("业务审核");
					boolean b = true;
					for (Role role2 : userRole) {
						if(role2.getRolename() == "业务审核"){
							b = false;
							break;
						}
					}
					if(b)
						userRole.add(r);
				}
			}
			
			
			JSONArray ja = new JSONArray();
			List<Menu> menuFirsts = menuService.queryLeftMenu(userID);
			if (menuFirsts.size() > 0) {
				for (Menu menu : menuFirsts) {
					JSONObject jsonFirst = JSONObject.fromObject(menu);
					if (null == menu.getMenufid()) {
						ja.add(jsonFirst);
					}
				}

				for (int i = 0; i < ja.size(); i++) {
					JSONObject jsonFirst = ja.getJSONObject(i);
					List<Menu> childLists = new ArrayList<Menu>();
					for (Menu menu1 : menuFirsts) {
						if (jsonFirst.getString("menuid").equals(menu1.getMenufid())) {
							childLists.add(menu1);
							
							if(menu1.getName().equals("全部")){    //绑定户的角色
								for (Role role : userRole) {
									Menu menuRole = new Menu();
									menuRole.setName(role.getRolename());
									menuRole.setMenucode(role.getRolename());
									menuRole.setUrl("index.html?type=" + role.getRolename());
									childLists.add(menuRole);
								}
							}
						}
						
					}
					if (childLists.size() > 0)
						jsonFirst.put("child", childLists);
				}

				jsonResult.put("datas", ja);
				result = 1;
				info = "查询成功！";
			} else {
				result = 0;
				info = "查询无数据!";
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = 2;
			info = "菜单加载异常!";
		}

		jsonResult.put("result", result);
		jsonResult.put("info", info);
		return jsonResult.toString();
	}

	@RequestMapping(value = "/list")
	public String list(@RequestBody JSONObject params) throws Exception {
		System.err.println(params);
		String result = "";

		ObjectMapper mapper = new ObjectMapper();

		int pageNum = 1;
		int pageSize = 10;
		if (params.has("pageNum")) {
			pageNum = params.getInt("pageNum");
			params.remove("pageNum");
		}
		if (params.has("pageSize")) {
			pageSize = params.getInt("pageSize");
			params.remove("pageSize");
		}

		Menu menu = mapper.readValue(params.toString(), Menu.class);

		List<Menu> menuList = menuService.findMenu(pageNum, pageSize, menu);

		// 获取分页信息
		PageInfo<Menu> page = new PageInfo<Menu>(menuList);

		JSONArray ja = JSONArray.fromObject(menuList);

//		JSONArray ja = new JSONArray();
//		for (Menu menuKey : menuList) {
//
//			JSONObject json = new JSONObject();
//			json.put("menuid", menuKey.getMenuid());
//			json.put("name", menuKey.getName());
//			json.put("remark", menuKey.getRemark());
//			json.put("url", menuKey.getUrl());
//			json.put("menufid", menuKey.getMenufid());
//			json.put("icon", menuKey.getIcon());
//			json.put("ifenable", menuKey.getIfenable());
//
//			ja.add(json);
//		}

		JSONObject jsonResult = new JSONObject();
		jsonResult.put("total", page.getTotal());
		jsonResult.put("rows", ja);

		result = jsonResult.toString();
		return result;
	}

	@RequestMapping(value = "/delete")
	public String delete(String menuid) throws Exception {
		int result = 0;
		String info = "";

		JSONArray japaram = new JSONArray();

		try {
			JSONObject param = new JSONObject();
			param.put("menuid", menuid);
			japaram.add(param);

			int delete = menuService.deleteByPrimaryKey(menuid);

			result = delete > 0 ? 1 : 0;
			info = delete > 0 ? "删除成功！" : "删除失败！";
		} catch (Exception e) {
			result = 2;
			info = "删除异常!";
		}

		JSONObject jsonResult = new JSONObject();
		jsonResult.put("result", result);
		jsonResult.put("info", info);
		jsonResult.put("datas", japaram);

		return jsonResult.toString();
	}

	@RequestMapping(value = "/save")
	public String save(@RequestBody JSONObject param) throws Exception {
		int result = 0;
		String info = "";
		boolean save = false;

		// 得到类型的model数据
		try {
			Menu menu = mapper.readValue(param.toString(), Menu.class);

			if (menu.getMenuid() != null) {
				save = menuService.updateData(menu);
			} else {
				save = menuService.saveData(menu);
			}
		} catch (Exception e) {
			result = 2;
			info = "数据保存异常！";
		}

		if (save) {
			result = 1;
			info = "数据保存成功！";
		} else {
			result = 0;
			info = "数据保存失败！";
		}

		JSONObject jsonResult = new JSONObject();
		jsonResult.put("result", result);
		jsonResult.put("info", info);

		return jsonResult.toString();
	}

	@RequestMapping(value = "/selectFid")
	public String fid() throws Exception {
		String result = "";

		List<Menu> menuList = menuService.selectFid();

		JSONArray ja = JSONArray.fromObject(menuList);

		JSONObject jsonResult = new JSONObject();
		jsonResult.put("rows", ja);

		result = jsonResult.toString();
		return result;
	}

	// @RequestMapping(value = "/update")
	// public String update(@RequestBody JSONObject param) throws Exception{
	// System.out.println("-----------"+param);
	// int result = 0;
	// String info = "";
	// boolean save = false;
	//
	// try{
	// Menu menu = mapper.readValue(param.toString(), Menu.class);
	//
	// save = menuService.updateData(menu);
	// }
	// catch(Exception e){
	// e.printStackTrace();
	// result = 2;
	// info = "数据保存异常！";
	// }
	//
	//
	// JSONObject jsonResult = new JSONObject();
	// if(save){
	// result = 1;
	// info = "数据保存成功！";
	// }
	// else{
	// result = 0;
	// info = "数据保存失败！";
	// }
	//
	//
	// jsonResult.put("result", result);
	// jsonResult.put("info", info);
	//
	// return jsonResult.toString();
	// }

	@RequestMapping(value = "/batchDelete")
	public String batchDelete(String menuids) throws Exception {
		int result = 0;
		String info = "";

		JSONArray japaram = new JSONArray();

		try {
			String menuidResult = "";

			for (int i = 0; i < menuids.split(",").length; i++) {
				String menuid = menuids.split(",")[i];
				int delete = menuService.deleteByPrimaryKey(menuid);

				if (delete > 0)
					menuidResult += menuid + ",";
			}

			menuidResult = menuidResult.substring(0, menuidResult.length() - 1);

			JSONObject param = new JSONObject();
			param.put("menuid", menuidResult);
			japaram.add(param);

			result = menuidResult.split(",").length > 0 ? 1 : 0;
			info = menuidResult.split(",").length > 0 ? "批量删除成功！" : "批量删除失败！";
		} catch (Exception e) {
			result = 2;
			info = "删除异常!";
		}

		JSONObject jsonResult = new JSONObject();
		jsonResult.put("result", result);
		jsonResult.put("info", info);
		jsonResult.put("datas", japaram);

		return jsonResult.toString();
	}

	@RequestMapping(value = "/selectFidOne")
	public String selectFidOne(String name) throws Exception {
		String result = "";

		List<Menu> menuList = menuService.selectChild();
		List<Menu> menu = menuService.selectFidOne(name);
		Menu menuname = new Menu();
		for (Menu menufidSingle : menu) {
			for (Menu menuidSingle : menuList) {
				if (menufidSingle.getMenuid().equals(menuidSingle.getMenuid())) {
					menuname = menuService.selectName(menuidSingle.getMenufid());
					menufidSingle.setMenufid(menuname.getName());
				}
			}

		}
		for (Menu menufidSingle : menu) {
			menufidSingle.setMenuid(null);
		}
		JSONArray ja = JSONArray.fromObject(menu);

		JSONObject jsonResult = new JSONObject();
		jsonResult.put("rows", ja);

		result = jsonResult.toString();
		return result;
	}

	@RequestMapping(value = "/queryAll")
	public String queryAll(String roleCode) throws Exception {// 菜单树查询
		List<MenuPermission> menuPermissions = menuPermissionService.queryByRoleCode(roleCode);
		// 获取一级菜单
		List<Menu> menuFirst = menuService.findLeftMenu(null);
		JSONArray ja = new JSONArray();

		if (menuFirst.size() > 0) {
			// 获取二级菜单
			for (Menu menu : menuFirst) {
				JSONObject jsonFirst = new JSONObject();
				jsonFirst.put("menuId", menu.getMenuid());
				jsonFirst.put("text", menu.getName());
				for (MenuPermission menuPermission : menuPermissions) {
					if (menuPermission.getMenuId().equals(menu.getMenuid())) {
						jsonFirst.put("state", "{\"checked\":true}");
					}
				}
				getChildNodes(menu.getMenuid(), menuPermissions, jsonFirst);
				ja.add(jsonFirst);
			}
		}
		System.err.println("菜单结果：" + ja);

		return ja.toString();
	}

	// 向下递归菜单
	private void getChildNodes(String id, List<MenuPermission> menuPermissions, JSONObject jsonFirst) throws Exception {
		List<Menu> menuSecond = menuService.findLeftMenu(id);
		if (menuSecond.size() > 0) {
			JSONArray cNodes = new JSONArray();
			for (Menu menu2 : menuSecond) {
				JSONObject cNode = new JSONObject();
				cNode.put("menuId", menu2.getMenuid());
				cNode.put("menuFid", menu2.getMenufid());
				cNode.put("text", menu2.getName());
				for (MenuPermission menuPermission : menuPermissions) {
					if (menuPermission.getMenuId().equals(menu2.getMenuid())) {
						cNode.put("state", "{\"checked\":true}");
					}
				}
				cNodes.add(cNode);
				getChildNodes(menu2.getMenuid(), menuPermissions, cNode);
			}
			jsonFirst.put("nodes", cNodes);
		}
	}

}
